% multi-channel transmitter and Lms equalizer simulation
% for fpga 
clc;
clear;
close all;

%% ------------------------------params-----------------------------
pilotLen = 1e6;
M = 4;
tapLen = 12;
ref = 6;
SNR = 28;
systemDelay = dsp.Delay(1);

%% ------------------------------data-----------------------------
load('testdata_eq_raw.mat');
x = floor(signal);
load('testdata_eq_rx.mat');
rx = floor(signal);
figure;subplot(211);bar(real(rx(1:100)));
subplot(212);bar(imag(rx(1:100)));
%% ------------------------------lms------------------------------
mu = 2^-5;% step size
weight = zeros(tapLen,1);
weight(floor(tapLen/2)) = 2047;
weight_delta_fifo = zeros(tapLen,5);
index = 1;
in = zeros(tapLen,1);
y = zeros(pilotLen-tapLen+1,1);
for i = tapLen:length(rx)
    %load data into sliding window, in(1):latest data
    in = rx(i:-1:i-tapLen+1);
    y(index) = floor(weight' * in /2^11);% calculate weighted output
    e = x(i-ref) - y(index);% calculate error
%    disp(y(index));
%    disp(x(i-ref));
%    disp(e);
    weight_delta = floor(conj(e) * in /2^11);
    weight_delta = floor(weight_delta * mu);
    weight_delta_fifo = [weight_delta_fifo(:,2:end),weight_delta];
    weight = weight + weight_delta_fifo(:,1);% update weight
    index = index + 1;
end
figure;plot(rx,'r*');hold on;plot(y,'bs');hold off;
title('MATLAB仿真——均衡前后星座图对比(mu=2^{-5})');legend('均衡前','均衡后');
figure;
subplot(211);bar(real(y(100000:100100)));
subplot(212);bar(imag(y(100000:100100)));